package com.kyomonn.talkischeap.CodingResources;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.kyomonn.talkischeap.WebViewActivity;

public class CodingResourcesItemAdapter extends BaseAdapter {
    private final Context context;
    private final int resource;
    private final String[] titles;
    private final String[] urls;

    public CodingResourcesItemAdapter(Context context, int resource, String[] titles, String[] urls) {
        this.context = context;
        this.resource = resource;
        this.titles = titles;
        this.urls = urls;
    }

    @Override
    public int getCount() {
        return titles.length;
    }

    @Override
    public Object getItem(int position) {
        return titles[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View view, ViewGroup viewGroup) {
        ViewHolder holder;

        if (view == null) {
            view = LayoutInflater.from(context).inflate(resource, viewGroup, false);
            TextView tv_title = (TextView) view;
            holder = new ViewHolder(tv_title);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }

        holder.bind(titles[position], new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(), WebViewActivity.class);
                intent.putExtra("url", urls[position]);
                view.getContext().startActivity(intent);
            }
        });

        return view;
    }

    static class ViewHolder {

        TextView view;

        public ViewHolder(TextView view) {
            this.view = view;
        }

        public void bind(String title, View.OnClickListener callback) {
            view.setText(title);
            view.setOnClickListener(callback);
        }
    }
}
